package cn.zmit.kuxi.activity;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory.Options;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Display;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import cn.zmit.kuxi.R;
import cn.zmit.kuxi.adapter.GridViewAddImageAdapter;
import cn.zmit.kuxi.contants.SPConstants;
import cn.zmit.kuxi.contants.Url;
import cn.zmit.kuxi.request.YBRDataRequestHandler;
import cn.zmit.kuxi.request.YBRRequest;
import cn.zmit.kuxi.request.YBRResponseHandler;
import cn.zmit.kuxi.utils.BitmapUtils;
import cn.zmit.kuxi.widget.MyGridView;

import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.xdroid.common.utils.FunctionUtils;
import com.xdroid.common.utils.PreferenceHelper;
import com.xdroid.common.utils.StringUtils;
import com.xdroid.common.utils.ToastUtils;
import com.xdroid.functions.request.JsonData;
import com.xdroid.request.extension.XDroidRequest;
import com.xdroid.request.extension.config.DataType;
import com.xdroid.request.extension.impl.OnRequestListenerAdapter;

/** * @author @parameter * @return */
public class NowShareActivity extends BaseActivity implements
		OnItemClickListener {
	@ViewInject(R.id.tv_now_title_join)
	private TextView tv_now_title_join;
	@ViewInject(R.id.tv_now_detail_data)
	private TextView tv_now_detail_data;
	@ViewInject(R.id.tv_luckNUM)
	private TextView tv_luckNUM;
	@ViewInject(R.id.edit_content)
	private EditText edit_content;
	@ViewInject(R.id.imag_upload)
	private ImageView imag_upload;
	@ViewInject(R.id.grid_share_pic)
	private MyGridView grid_share_pic;
	private String userId, gp_id;
	@ViewInject(R.id.root)
	private RelativeLayout root;
	@ViewInject(R.id.rl_dialog_ios_7_root)
	private RelativeLayout mDialogRootRelativeLayout;

	@ViewInject(R.id.ll_dialog_ios_7_cotent)
	private LinearLayout mDialogCotentLinearLayout;
	private final static int REQUEST_CODE_GALLERY = 0x11;
	private final static int REQUEST_CODE_CAMERA = 0x12;
	// 当前图片路径
	String imagePath = null;
	private GridViewAddImageAdapter gvaiadpter;
	private List<Bitmap> list = new ArrayList<Bitmap>();
	private List<String> list_url = new ArrayList<String>();
	Bitmap resultBitmap = null;
	private int size = 0;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setTitleView("立即晒单", true);
		setContentView(R.layout.activity_now_share);
		ViewUtils.inject(this);
		edit_content.setSingleLine(false);
		edit_content.setHorizontallyScrolling(false);
		initView();
		init();
		root.setOnTouchListener(new OnTouchListener() {

			@SuppressLint("ClickableViewAccessibility")
			@Override
			public boolean onTouch(View arg0, MotionEvent arg1) {
				InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);

				return inputMethodManager.hideSoftInputFromWindow(
						getCurrentFocus().getWindowToken(), 0);
			}
		});
	}

	private void init() {
		gvaiadpter = new GridViewAddImageAdapter(this, list);
		grid_share_pic.setOnItemClickListener(this);
		grid_share_pic.setAdapter(gvaiadpter);
		gvaiadpter.setList(list);
	}

	private void initView() {
		String title = getTextFromBundle("title");
		String goodsName = getTextFromBundle("goodsName");
		gp_id = getTextFromBundle("gp_id");
		String luckyNum = getTextFromBundle("lunckyNum");
		tv_now_title_join.setText("第" + title + "期");
		tv_now_detail_data.setText(goodsName);
		int num = Integer.parseInt(luckyNum);
		int luck = num;
		tv_luckNUM.setText("幸运号：" + luck + "");
		Boolean haslogin = PreferenceHelper.readBoolean(this,
				SPConstants.SHARED_PREFERENCE_NAME, SPConstants.HAS_LOGGED,
				false);
		if (haslogin) {
			userId = PreferenceHelper.readString(this,
					SPConstants.SHARED_PREFERENCE_NAME, SPConstants.USERID, "");
		}
	}

	@OnClick({ R.id.btn_commit_order, R.id.imag_upload, R.id.tv_select_camera,
			R.id.tv_select_gallery, R.id.tv_cancel })
	private void OnClick(View v) {
		switch (v.getId()) {
		case R.id.btn_commit_order:// 提交
			List<File> file = new ArrayList<File>();
			if (list_url != null && list_url.size() > 0) {

				for (int i = 0; i < list_url.size(); i++) {
					File files = new File(list_url.get(i));
					file.add(files);
				}
				RequestToPostMessage(file.toArray(new File[] {}),
						new YBRDataRequestHandler<String>() {

							@Override
							public void OnSuccess(String argT) {
								dismissProgressDialog();
								JsonData jsonData = JsonData.create(argT);
								if (jsonData != null
										&& jsonData.optString("code").equals(
												"1")) {
									ToastUtils.show(context, "提交成功");
									Log.e("post picture===", "success");
									finish();
								}
							}

							@Override
							public void OnFailure(String argT) {
								Log.e("post picture===", "failure");
								ToastUtils.show(context, "提交失败");
							}
						});

			} else {
				File[] files = new File[] {};
				RequestToPostMessage(files,
						new YBRDataRequestHandler<String>() {

							@Override
							public void OnSuccess(String argT) {
								dismissProgressDialog();
								JsonData jsonData = JsonData.create(argT);
								if (jsonData != null
										&& jsonData.optString("code").equals(
												"1")) {
									ToastUtils.show(context, "提交成功");
									Log.e("post text===", "success");
									finish();
								}
							}

							@Override
							public void OnFailure(String argT) {
								dismissProgressDialog();
								Log.e("post text===", "failure");
								ToastUtils.show(context, "评价失败");
							}
						});
			}
			break;
		case R.id.imag_upload:// 手机晒图
			openDialog();
			break;
		case R.id.tv_select_camera:// 照相机
			closeDialog();
			// imagePath = FunctionUtils.chooseImageFromCamera(
			// NowShareActivity.this, REQUEST_CODE_CAMERA, "cameraImage");
			// 设置相机拍照后照片保存路径
			pictureFile = new File(Environment.getExternalStorageDirectory(),
					"picture" + System.currentTimeMillis() / 1000 + ".jpg");
			// 启动拍照,并保存到临时文件
			Intent intentCam = new Intent();
			intentCam.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
			intentCam.putExtra(MediaStore.EXTRA_OUTPUT,
					Uri.fromFile(pictureFile));
			intentCam.putExtra(MediaStore.Images.Media.ORIENTATION, 0);
			startActivityForResult(intentCam, REQUEST_CAMERA_IMAGE);
			break;
		case R.id.tv_select_gallery:// 相册
			closeDialog();
			// FunctionUtils.chooseImageFromGallery(NowShareActivity.this,
			// REQUEST_CODE_GALLERY);
			Intent intentCho = new Intent();
			intentCho.setType("image/*");
			intentCho.setAction(Intent.ACTION_PICK);
			startActivityForResult(intentCho, REQUEST_CODE_GALLERY);
			break;
		case R.id.tv_cancel:// 取消
			closeDialog();
			break;

		default:
			break;
		}
	}

	// 晒图弹窗
	private void closeDialog() {
		performDialogAnimation(mDialogRootRelativeLayout,
				mDialogCotentLinearLayout, false);
	}

	private void openDialog() {
		performDialogAnimation(mDialogRootRelativeLayout,
				mDialogCotentLinearLayout, true);
	}

	/**
	 * 提交请求
	 */
	private class onRequestListener extends OnRequestListenerAdapter<Object> {
		@Override
		public void onDone(XDroidRequest<?> request, String response,
				DataType dataType) {
			super.onDone(request, response, dataType);
			dismissProgressDialog();
			JsonData jsonData = JsonData.create(response);
			String data = jsonData.optString("code");
			if (data != null && data.length() > 0) {
				ToastUtils.show(context, "晒单成功");
			}
		}

		@Override
		public void onRequestPrepare() {
			super.onRequestPrepare();
			showProgressDialog("正在提交……");

		}

		@Override
		public void onRequestFailed(String error) {
			super.onRequestFailed(error);
			dismissProgressDialog();
		}
	}

	/**
	 * @author Joash_Yan
	 */
	// 这是选图和拍照相关
	private static final int REQUEST_PICTURE_CHOOSE = 1;
	private static final int REQUEST_CAMERA_IMAGE = 2;
	private File pictureFile;
	private Bitmap img = null;
	private byte[] imgData = null;
	static String fileSrc = null;

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
		case REQUEST_CODE_GALLERY:
			// imagePath = FunctionUtils
			// .onActivityResultForChooseImageFromGallery(context,
			// requestCode, resultCode, data);

			if ("file".equals(data.getData().getScheme())) {
				// 有些低版本机型返回的Uri模式为file
				fileSrc = data.getData().getPath();
			} else {
				// Uri模型为content
				String[] proj = { MediaStore.Images.Media.DATA };
				Cursor cursor = getContentResolver().query(data.getData(),
						proj, null, null, null);
				cursor.moveToFirst();
				int idx = cursor
						.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
				fileSrc = cursor.getString(idx);
				cursor.close();
			}
			break;
		case REQUEST_CAMERA_IMAGE:
			// 设置相机拍照后照片保存路径
			if (null == pictureFile) {
				Toast.makeText(context, "拍照失败，请重试", 0).show();
				return;
			}

			fileSrc = pictureFile.getAbsolutePath();
			updateGallery(fileSrc);

			break;

		default:
			break;
		}

		// img = BitmapUtils.decodeSampledBitmapFromResource(fileSrc, 50, 50);

		// 获取图片的宽和高
		Options options = new Options();
		options.inJustDecodeBounds = true;
		img = BitmapFactory.decodeFile(fileSrc, options);

		// 压缩图片
		options.inSampleSize = Math.max(1, (int) Math.ceil(Math.max(
				(double) options.outWidth / 1024f,
				(double) options.outHeight / 1024f)));
		options.inJustDecodeBounds = false;
		img = BitmapFactory.decodeFile(fileSrc, options);

		// 部分手机会对图片做旋转，这里检测旋转角度
		int degree = readPictureDegree(fileSrc);
		if (degree != 0) {
			// 把图片旋转为正的方向
			img = rotateImage(degree, img);
		}

		ByteArrayOutputStream baos = new ByteArrayOutputStream();

		// 可根据流量及网络状况对图片进行压缩
		img.compress(Bitmap.CompressFormat.JPEG, 30, baos);
		imgData = baos.toByteArray();

		// 添加至界面listview
		saveBitmap2file(img, fileSrc);
		list.add(img);

		list_url.add(fileSrc);
		gvaiadpter.setList(list);
		size++;
	}

	// saveBitmap2file
	static boolean saveBitmap2file(Bitmap bmp, String filename) {
		CompressFormat format = Bitmap.CompressFormat.JPEG;
		int quality = 50;
		OutputStream stream = null;
		try {
			stream = new FileOutputStream(fileSrc);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}

		return bmp.compress(format, quality, stream);
	}

	/**
	 * 读取图片属性：旋转的角度
	 * 
	 * @param path
	 *            图片绝对路径
	 * @return degree旋转的角度
	 */
	public static int readPictureDegree(String path) {
		int degree = 0;
		try {
			ExifInterface exifInterface = new ExifInterface(path);
			int orientation = exifInterface.getAttributeInt(
					ExifInterface.TAG_ORIENTATION,
					ExifInterface.ORIENTATION_NORMAL);
			switch (orientation) {
			case ExifInterface.ORIENTATION_ROTATE_90:
				degree = 90;
				break;
			case ExifInterface.ORIENTATION_ROTATE_180:
				degree = 180;
				break;
			case ExifInterface.ORIENTATION_ROTATE_270:
				degree = 270;
				break;
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return degree;
	}

	/**
	 * 
	 * 
	 * @param filename
	 */
	private void updateGallery(String filename) {
		MediaScannerConnection.scanFile(this, new String[] { filename }, null,
				new MediaScannerConnection.OnScanCompletedListener() {

					@Override
					public void onScanCompleted(String arg0, Uri arg1) {
						Log.e("successed===", "nowshare_gallery");
					}
				});
	}

	/**
	 * 旋转图片
	 * 
	 * @param angle
	 * @param bitmap
	 * @return Bitmap
	 */
	public static Bitmap rotateImage(int angle, Bitmap bitmap) {
		// 图片旋转矩阵
		Matrix matrix = new Matrix();
		matrix.postRotate(angle);
		// 得到旋转后的图片
		Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0,
				bitmap.getWidth(), bitmap.getHeight(), matrix, true);
		return resizedBitmap;
	}

	// ////////////////////////////////////////////////////////////////////////////////////////

	/**
	 * 转换原图，进行缩放处理
	 * 
	 * @return 转换后的Bitmap
	 */
	private Bitmap convertFullBitmap(String ImagePath) {
		BitmapFactory.Options options = new BitmapFactory.Options();
		options.inJustDecodeBounds = true;
		String FilePath = ImagePath;
		Bitmap bm = BitmapFactory.decodeFile(FilePath, options);
		WindowManager windowManager = getWindowManager();
		Display windowDisplay = windowManager.getDefaultDisplay();
		int windowWidth = windowDisplay.getWidth();
		int scale = 1;
		if (options.outWidth > windowWidth) {
			scale = options.outWidth / windowWidth;
		}
		options.inJustDecodeBounds = false;
		options.inSampleSize = scale;
		bm = BitmapFactory.decodeFile(FilePath, options);
		return bm;

	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		// TODO Auto-generated method stub
		list.remove(arg2);
		gvaiadpter.setList(list);
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		if (size == 8) {
			imag_upload.setClickable(false);
		}
	}

	private void RequestToPostMessage(File[] files,
			YBRDataRequestHandler<String> ybrDataRequestHandler) {
		YBRResponseHandler<String> pHandler = new YBRResponseHandler<String>(
				ybrDataRequestHandler) {

			@Override
			public void OnSuccess(YBRRequest argRequest) {
				if (m_pDataRequestHandler != null) {
					m_pDataRequestHandler.OnSuccess(argRequest
							.getM_pResponseJson().toString());
				}

			}

			@Override
			public void OnFailure(YBRRequest argRequest) {
				if (m_pDataRequestHandler != null) {
					m_pDataRequestHandler.OnFailure(argRequest
							.getM_pResponseJson().toString());
				}

			}

		};
		YBRRequest pRequest = new YBRRequest(Url.SHARE, "", pHandler);
		String content = edit_content.getText().toString().trim();
		if (StringUtils.isEmpty(content)) {
			ToastUtils.show(context, "请输入评价内容");
			return;
		}
		pRequest.SetParamValue(content, "content");
		pRequest.SetParamValue(userId, "user_id");
		pRequest.SetParamValue(gp_id, "gp_id");
		try {
			pRequest.AddImageData(files, "pictures[]");
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// 开启请求
		pRequest.setM_bSilent(true);
		pRequest.StartRequest();

	}
}
